package win.somereason.test.baseline_web.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

/**
 * Created by Qingsheng.Sun on 2018/3/28.
 * spring security配置核心类
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 获取用户实体的方式.
     * @return
     */
    @Bean
    SecUserDetailsService customUserService() { //注册UserDetailsService 的bean
        return new SecUserDetailsService();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint())
                .and().csrf().disable()
                .authorizeRequests().antMatchers("/sec/*").permitAll().anyRequest().authenticated().and()
                .formLogin()
                .loginPage("/sec/login")//登录页
                .loginProcessingUrl("/login") //验证登录的url,在form模式和ajax模式,都是这个地址.
                .usernameParameter("username").passwordParameter("password")//登录时,传递参数的名字
                //.defaultSuccessUrl("/home/index").failureUrl("/sec/login?error=true")// 如果用form模式登录,通常设置这两个,否则要屏蔽,然后用successHandler处理
                .successHandler(new AjaxAuthSuccessHandler()).failureHandler(new AjaxAuthFailHandler())
                .and().httpBasic()
                .and().rememberMe().rememberMeParameter("remembermeee");
    }

    /**
     * 当用户名密码存在数据库或者其他地方时
     *
     * passwordEncoder通常使用BCryptPasswordEncoder,存密码的时候,使用BCryptPasswordEncoder.encode()
     *
     * @param auth
     * @throws Exception
     */
    @Autowired
    protected void configureDataBase(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(customUserService())
                .passwordEncoder(NoOpPasswordEncoder.getInstance()); //user Details Service验证
    }

    /**
     * 用户名密码写死在程序里,和前者可以共存
     *
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureProgramed(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("aaa")
                .password("{noop}123")// 保证密码匹配的时候不要加密
                .roles("USER");
    }

}